#!/bin/bash
#Author: YangYi
#Date: 2025-08-25
#Version: v1
#Content nginx日志切割



# 检查是否传入了参数
if [ -z "$1" ]; then
  echo "Usage: $0 <请输入您要查询的路径: 例 /app/ctgslb>"
  exit 1
fi
 
# nginx日志切割路径,根据环境填写
NGINXPATH=$1

# 初始化全局变量
nginxExample=""
 
function modifyNginxLog {

  # 在 /app 目录下查找以 inst_ 开头的目录
  inst_dirs=$(find $NGINXPATH -type d -name "inst_*")
 
  # 遍历每个找到的目录
  for dir in $inst_dirs; do
    # 检查当前 inst_ 开头的目录下是否有名为 nginx 的目录
    if find "$dir" -type d -name "nginx" | grep -q .; then
      # 将符合条件的 inst_ 目录路径追加到 nginxExample 变量中
      nginxExample="$nginxExample$dir"$'\n'
    fi
  done
 
  # 输出找到的目录列表
  echo "已查询包含nginx实例为: "
  echo -e "$nginxExample"
 
  # 逐行遍历 nginxExample 变量内容，并检查路径是否存在
  #echo "Checking paths with 'ls -l':"
  #while IFS= read -r path; do
  #  if [ -d "$path" ]; then
   #   echo "Path exists: $path"
    # ls -l "$path/nginx"
    #else
    #  echo "Path does not exist: $path"
    #fi
  #done <<< "$nginxExample"

}


#用户输入
function UserInput {

  while true; do
    # 提示输入
    read -p "确认是否执行日志切割脚本？(Y/y 执行, N/n 退出): " choice

    # 根据输入进行判断
    case "$choice" in
        [Yy]* )
            logrotateTemplate  # 调用函数
            break        # 执行完后退出循环
            ;;
        [Nn]* )
            echo "退出脚本。"
            break        # 退出循环
            ;;
        * )
            echo "无效输入，请输入 Y/y 或 N/n。"
            ;;
    esac
  done
}


function logrotateTemplate {

  # 模板内容
  template='{
	daily
	rotate 10
	maxsize 100M
	missingok
	dateext
	nocompress
	delaycompress
	notifempty
	sharedscripts
	create 0644 root root
	postrotate
		[ -e nginxPath/nginx/logs/nginx.pid ] && /bin/kill -USR1 `cat nginxPath/nginx/logs/nginx.pid`
	endscript
  }'
 
  # 逐行读取 nginxExample
  while IFS= read -r line; do
    
    # 检查是否为空行
    if [[ -n "$line" ]]; then

    # 创建文件名
    filename=`echo -e "${line}" | awk -F "/" '{print $NF}'`

    # 替换模板中的 nginxPath
    customizedTemplate=$(echo "$template" | sed "s|nginxPath|$line|g")

    # 写入文件
    {
        echo "${line}/nginx/logs/access.log"
        echo "${line}/nginx/logs/error.log"
        echo "${line}/keepalived/log/keepalived.log"
        echo "${line}/keepalived/log/keepalived_vrrp.log"
        echo ""
        echo "$customizedTemplate"
    } > "/etc/logrotate.d/$filename"
    fi
  done <<< "$nginxExample"
  echo "脚本执行完成,执行命令查看:=====>   ls -l /etc/logrotate.d/ | grep 'inst_'"
}

modifyNginxLog
UserInput

